<template>
  <Page class="bg-[#f5f5f5] min-h-screen">
    <PageHeader title="课程列表" />
    <view class="h-[120rpx]"></view>
    <!-- 课程列表 -->
    <view class="p-[24rpx]">
      <view v-if="filteredCourses.length">
        <view
          v-for="item in filteredCourses"
          :key="item.id"
          class="bg-white rounded-2xl shadow-md p-[28rpx] mb-[24rpx] flex gap-x-4 items-center"
          @click="handleCourseClick(item)"
        >
          <image :src="getFullPath(item.cover)" class="w-[140rpx] h-[140rpx] rounded-xl object-cover bg-[#e6eaf2] mr-[24rpx]" />
          <view class="flex-1 min-w-0">
            <view class="font-bold text-[30rpx] mb-[10rpx] line-clamp-2">{{ item.title }}</view>
            <view class="flex gap-x-8 text-[24rpx] text-[#666] mb-[8rpx]">
              <view>{{ item.member_number }}人学习</view>
              <!-- 获取的数据中没有课时-->
              <view>{{ item.cycle }}课时</view>
            </view>
            <view class="text-[#FF4D4F] text-[30rpx] font-bold">¥{{ item.price }}</view>
          </view>
        </view>
      </view>
      <view v-else class="text-center py-[100rpx] text-[#999] text-[28rpx]">暂无课程</view>
    </view>
    <!-- 底部下一页 -->
    <view class="flex justify-center items-center py-[32rpx]">
      <nut-button type="primary" class="rounded-2xl text-[28rpx] px-[64rpx] bg-[#165DFF]" @click="loadMore" :disabled="noMore">{{ noMore ? '没有更多了' : '下一页' }}</nut-button>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import PageHeader from '@/components/PageHeader.vue'
import {getFullPath, post} from "@/utils/request";

/**
 * 课程列表页面
 * @description 顶部tab切换分类，课程列表，下拉刷新，底部下一页，严格按设计稿和Cursor规则实现。
 * @performance 只渲染当前tab内容，mock数据，移动端适配。
 */
//获取课程数据的格式
interface CourseColumn {
  member_id:null,
  teachers_pic:null,
  sign_rate:null,
  teacher_name:null,
  member_number:null,
  teachers_introduction:null,
  create_time: number,
  pay_number:null,
  title:null,
  type:null,
  cycle_type:null,
  cycle:null,
  cover:null,
  update_time: null | number;
  pay_status:null,
  total_amount:null,
  price:null,
  progress:null,
  id: number,
  introduction:null,
  status:number
}

interface CourseItem {
  columns: CourseColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface QueryParams{
  id?: number;               // 整数类型，可选
  pageNo?: number;           // 分页查询-第几页，整数类型，可选
  pageSize?: number;         // 分页查询-每页条数，整数类型，可选
  trainingId?: number;       // 主课程ID，整数类型，可选
  title?: string;            // 标题，字符串类型，可选
  dateTime?: string;         // 日期时间，字符串类型（格式如：'2023-10-01 12:00'），可选
  duration?: string;         // 时长(分钟)，字符串类型，可选
  videoUrl?: string;         // 视频URL地址，字符串类型，可选
  type?: number;             // 类型，整数类型，可选
}

const tabs = ['全部', '前端', '后端', '移动', '设计']
const activeTab = ref(0)
const refreshing = ref(false)
const page = ref(1)
const pageSize = 6
const noMore = ref(false)
const loading = ref(false)

const allCourses = ref([
  { id: 1, title: 'JavaScript高级程序设计', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 128, cycle: 36, price: 199, category: '前端' },
  { id: 2, title: 'Vue.js从入门到实战', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 98, cycle: 24, price: 129, category: '前端' },
  { id: 3, title: 'React Native跨平台开发', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 76, cycle: 30, price: 159, category: '移动' },
  { id: 4, title: 'Node.js后端开发', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 54, cycle: 28, price: 149, category: '后端' },
  { id: 5, title: 'HTML5与CSS3基础教程', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 128, cycle: 20, price: 99, category: '前端' },
  { id: 6, title: 'UI设计基础', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 60, cycle: 18, price: 89, category: '设计' },
  { id: 7, title: '小程序开发实战', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 80, cycle: 22, price: 139, category: '移动' },
  { id: 8, title: 'Python全栈开发', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 110, cycle: 40, price: 209, category: '后端' },
  { id: 9, title: 'Web前端工程化', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 70, cycle: 16, price: 119, category: '前端' },
  { id: 10, title: '移动端UI设计', cover: 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg', member_number: 45, cycle: 12, price: 79, category: '设计' }
])

const filteredCourses = ref([] as typeof allCourses.value)

/**
 * 获取所有课程
 */
function filterCourses() {
  const queryParams: QueryParams = {
    pageNo: 1,           // 第1页
    pageSize: 20,        // 每页10条
    //trainingId: 123,
    type: 0
  };
  post('/training/all',queryParams).then(res => {
    //console.log("res",res)
    //TODO:获取的数据中“课时”为cycle
    allCourses.value = res.data.map((item: CourseItem) => ({
      title: item.columns.title,
      price: item.columns.price,
      member_id: item.columns.member_id,
      member_number: item.columns.member_number,
      create_time: item.columns.create_time,
      type: item.columns.type,
      id: item.columns.id,
      cycle:item.columns.cycle,
      cover:item.columns.cover,
      teachers_pic:item.columns.teachers_pic
    }));
    //console.log("课程列表",allCourses.value)
  })
  //分页
  let list = allCourses.value
  if (activeTab.value > 0) {
    list = list.filter(c => c.category === tabs[activeTab.value])
  }
  filteredCourses.value = list.slice(0, page.value * pageSize)
  noMore.value = filteredCourses.value.length >= list.length
}

function switchTab(idx: number) {
  activeTab.value = idx
  page.value = 1
  noMore.value = false
  filterCourses()
}

function loadData() {
  page.value = 1
  noMore.value = false
  filterCourses()
}

function onRefresh() {
  setTimeout(() => {
    loadData()
    refreshing.value = false
  }, 800)
}

function fetchRecords() {
  if (noMore.value || loading.value) return
  loading.value = true
  setTimeout(() => {
    page.value += 1
    filterCourses()
    loading.value = false
  }, 800)
}

function loadMore() {
  fetchRecords()
}

// Taro原生下拉刷新（小程序/APP）
usePullDownRefresh(() => {
  loadData()
  setTimeout(() => {
    Taro.stopPullDownRefresh()
  }, 1000)
})

// Taro原生触底加载下一页（小程序/APP）
useReachBottom(() => {
  fetchRecords()
})
// 处理课程点击，现在点击即可进入课程详情页
const handleCourseClick = (item:any) => {
  //console.log("item",item.id)
  // Taro.showToast({
  //   title: `即将进入课程: ${title}`,
  //   icon: "none",
  //   duration: 2000,
  // });
  Taro.navigateTo({
    url: `/pages/course/detail?id=${item.id}`,
  });
};
// 初始化
onMounted(() => {
  filterCourses()
})
</script> 